package com.zkthink.ceres.common.utils;

import com.zkthink.exception.BizException;
import io.rong.RongCloud;
import io.rong.messages.VoiceMessage;
import io.rong.methods.chatroom.Chatroom;
import io.rong.methods.message._private.Private;
import io.rong.methods.message.expansion.Expansion;
import io.rong.methods.sensitive.SensitiveWord;
import io.rong.methods.user.User;
import io.rong.models.Result;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.message.ExpansionModel;
import io.rong.models.message.PrivateMessage;
import io.rong.models.response.ChatroomUserQueryResult;
import io.rong.models.response.ListWordfilterResult;
import io.rong.models.response.ResponseResult;
import io.rong.models.response.TokenResult;
import io.rong.models.sensitiveword.SensitiveWordModel;
import io.rong.models.user.UserModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;

/**
 * @Author Xiaoyan
 * @create 2022/1/6 13:59
 */
@Configuration
public class RongCloudUtils {
    //应用key
    public static String app_key;
    //应用密钥
    public static String app_sercet;


    @Value("${rongcloud.app-key:}")
    private String appKey;
    @Value("${rongcloud.app-secret:}")
    private String appSecret;


    @PostConstruct
    public void init() {
        app_key = appKey;
        app_sercet = appSecret;
        System.out.println("---初始化开放平台api参数---appKey---" + app_key + "---appSecret---" + app_sercet + "---");
    }


    /**
     * @param userId
     * @param nickname
     * @param headimg
     * @return
     */
    public static String getToken(Long userId, String nickname, String headimg) {

        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        User user = rongCloud.user;
        UserModel userModel = new UserModel()
                .setId(String.valueOf(userId))
                .setName(nickname)
                .setPortrait(headimg);
        try {
            TokenResult result = user.register(userModel);
            if (result.getCode() == 200) {
                return result.getToken();
            } else {
                throw new BizException(result.errorMessage);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }
//    /**
//     *
//     * API 文档: https://docs.rongcloud.cn/v4/5X/views/im/server/user/expire.html
//     *
//     * Token 失效
//     */
//    public static String getToken(Long userId,String nickname,String headimg) {
//        ExpireModel expireModel = new ExpireModel()
//                .setUserId(new String[]{"CHIQ1"})
//                .setTime(1623123911000L);
//        refreshResult = User.expire(expireModel);
//        System.out.println("expire:  " + refreshResult.toString());
//    }

    /**
     * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/user/user.html#refresh
     * <p>
     * 刷新用户信息方法
     */
    public static void updateUserInfo(Long userId, String nickname, String headimg) {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        User user = rongCloud.user;

        UserModel userModel = new UserModel()
                .setId(String.valueOf(userId))
                .setName(nickname)
                .setPortrait(headimg);
        try {
            Result refreshResult = user.update(userModel);
            if (refreshResult.getCode() == 200) {

            } else {
                throw new BizException(refreshResult.errorMessage);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }


    /**
     * 创建聊天室
     *
     * @param chatroomId
     * @param chatroomName
     */
    public static void createChatRoom(String chatroomId, String chatroomName) {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);

        Chatroom chatroom = rongCloud.chatroom;

        ChatroomModel[] chatrooms = {
                new ChatroomModel().setId(chatroomId).setName(chatroomName)
        };

        try {
            ResponseResult result = chatroom.create(chatrooms);
            if (result.getCode() == 200) {
                System.out.println("create:  " + result.toString());
            } else {
                throw new BizException(result.errorMessage);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 销毁聊天室
     *
     * @param chatroomId
     */
    public static void destoryChatRoom(String chatroomId) {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);

        Chatroom chatroom = rongCloud.chatroom;

        ChatroomModel chatroomModel = new ChatroomModel()
                .setId(chatroomId);

        //ResponseResult chatroomDestroyResult = chatroom.destroy(chatroomModel);
        //System.out.println("destroy:  " + chatroomDestroyResult.toString());

        try {
            ResponseResult result = chatroom.destroy(chatroomModel);
            if (result.getCode() == 200) {
                System.out.println("destroy:  " + result.toString());
            } else {
                throw new BizException(result.errorMessage);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 获取聊天室信息
     *
     * @param roomId
     */
    public static ChatroomUserQueryResult getChatRoom(String roomId) {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);

        Chatroom chatroom = rongCloud.chatroom;

        ChatroomModel chatroomModel = new ChatroomModel()
                .setId(roomId)
                .setCount(500)
                .setOrder(1);

        try {
            ChatroomUserQueryResult chatroomQueryUserResult = chatroom.get(chatroomModel);
            if (chatroomQueryUserResult.getCode() == 200) {
                return chatroomQueryUserResult;
            } else {
                throw new BizException(chatroomQueryUserResult.errorMessage);
            }
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }
    }


    /**
     * API 文档: http://www.rongcloud.cn/docs/server_sdk_api/message/private.html#send
     * <p>
     * 发送单聊消息<文本, 语音, 文件类型 等消息类型>
     */
    public static void sendMessage() {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        VoiceMessage voiceMessage = new VoiceMessage("hello", "helloExtra", 20L);
        Private Private = rongCloud.message.msgPrivate;
        PrivateMessage privateMessage = new PrivateMessage()
                .setSenderId("2609751433442958892")
                .setTargetId(new String[]{"2609751433121"})
                .setObjectName(voiceMessage.getType())
                .setContent(voiceMessage)
                .setPushContent("")
                .setPushData("{\"pushData\":\"hello\"}")
                .setPushExt("{\"title\":\"\",\"forceShowPushContent\":0,\"pushConfigs\":{\"HW\":{\"channelId\":\"\"},\"MI\":{\"channelId\":\"\"},\"OPPO\":{\"channelId\":\"\"}}}")
                .setCount("4")
                .setVerifyBlacklist(0)
                .setIsPersisted(0)
                .setIsCounted(0)
                .setIsIncludeSender(0);
        try {
            ResponseResult privateResult = Private.send(privateMessage);
            System.out.println("send private getReqBody:  " + privateResult.getReqBody());
            System.out.println("send private message:  " + privateResult.toString());
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }

    }

    /**
     * API 文档: https://doc.rongcloud.cn/imserver/server/v1/message/expansion#set
     * <p>
     * 设置消息扩展
     */
    public static void sendExpansionMessage() {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        Expansion expansion = rongCloud.expansion;
        ExpansionModel msg = new ExpansionModel();
        msg.setMsgUID("BS45-NPH4-HV87-10LM");
        msg.setUserId("WNYZbMqpH");
        msg.setTargetId("tjw3zbMrU");
        msg.setConversationType(1);
        HashMap<String, String> kv = new HashMap<String, String>();
        kv.put("type1", "1");
        kv.put("type2", "2");
        kv.put("type3", "3");
        kv.put("type4", "4");
        msg.setExtraKeyVal(kv);
        ResponseResult result = null;
        try {
            result = expansion.set(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("set expansion:  " + result.toString());
    }

    /**
     * 得到敏感词
     *
     * @return
     * @throws Exception
     */
    public static String getSensitiveword() throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        //自定义 api 地址方式
        // RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);

        SensitiveWord sensitiveWord = rongCloud.sensitiveword;
        ListWordfilterResult result = sensitiveWord.getList(1);
        System.out.println("getList:  " + result.toString());
        String s = result.toString();
        return s;
    }

    /**
     * 移除敏感词
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static void removeSensitiveword(String word) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        //自定义 api 地址方式
        // RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);

        SensitiveWord sensitiveWord = rongCloud.sensitiveword;
        ResponseResult removeesult = sensitiveWord.remove(word);
        System.out.println("SensitivewordDelete:  " + removeesult.toString());
    }

    /**
     * 批量移除敏感词
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static void removeSensitivewordList(String[] word) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        SensitiveWord sensitiveWord = rongCloud.sensitiveword;
        ResponseResult batchDeleteResult = sensitiveWord.batchDelete(word);
        System.out.println("SensitivewordbatchDelete:  " + batchDeleteResult.toString());
    }


    /**
     * 添加敏感词
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static void addSensitivewordList(String word) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        SensitiveWord sensitiveWord = rongCloud.sensitiveword;
        SensitiveWordModel sentiveWord = new SensitiveWordModel()
                .setType(1)
                .setKeyword(word);
        ResponseResult addersult = sensitiveWord.add(sentiveWord);
        System.out.println("sentiveWord  add replace :  " + addersult.toString());

    }


    /**
     * 添加替换敏感词
     *
     * @param word
     * @return
     * @throws Exception
     */
    public static void addReplaceSensitivewordList(String word, String replace) throws Exception {
        RongCloud rongCloud = RongCloud.getInstance(app_key, app_sercet);
        SensitiveWord sensitiveWord = rongCloud.sensitiveword;
        SensitiveWordModel sentiveWord = new SensitiveWordModel()
                .setType(0)
                .setKeyword(word)
                .setReplace(replace);
        ResponseResult addesult = sensitiveWord.add(sentiveWord);
        System.out.println("sentiveWord  add replace :  " + addesult.toString());

    }

}
